﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Net;
using System.Xml.Linq;

namespace com.codeplex.eatoutadvocate.Web.Mvc.Services
{
    public class LocationService
    {
        private string manualZipCode;
        public string ManualZipCode
        {
            get { return manualZipCode; }
            set
            {
                manualZipCode = value;
            }
        }

        public string GetZipCode()
        {
            //Get API Keys first
            string ipaddress = "";
            string appKey = "";
            string url = "http://api.ipinfodb.com/v2/ip_query.php?key={0}&ip={1}";
            //&timezone=true is not required in the URL

            url = String.Format(url, appKey, ipaddress);
            HttpWebRequest httpWRequest = WebRequest.Create(url) as HttpWebRequest;
            using (HttpWebResponse httpWResponse = httpWRequest.GetResponse() as HttpWebResponse)
            {
                var result = XDocument.Load(httpWResponse.GetResponseStream());

                // Get first Zip Code from the result
                var zip = (from x in result.Descendants("Response")
                                select x.Element("ZipPostalCode").Value
                                ).First();
                return zip as string;
            }
        }

    }
}